#include "widget.h"
#include "ui_widget.h"
#include <sstream>
#include <string>

Widget::Widget(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Widget)
{
    ui->setupUi(this);
}

Widget::~Widget()
{
    delete ui;
}
void Widget::read(){

    std::string str = ui->PTE_input->toPlainText().toStdString();
    std::stringstream ss(str);
    num = 0 ;
    while(ss>>dx[num]>>dy[num]){
        num++;
    }
    tmpx = ui->LE_input->text().toDouble();
}
double Widget::get_la_ln(int x,double val){
    double ret = 1;
    for(int i=0;i<num;++i){
        if(i!=x){
            ret *=(val-dx[i]);
            ret /=(dx[x]-dx[i]);
        }
    }
    return ret;
}
double Widget::lagrange(){
    double ans = 0;
    for(int i=0;i<num;++i){
        ans += get_la_ln(i,tmpx)*dy[i];
    }
    return ans;
}
void Widget::get_table(){
    for(int i=0;i<num;i++){
        dtable[0][i]=dx[i];
    }
    for(int i=1;i<num;i++){
        for(int j=0;j<num-i;j++){
            dtable[i][j]=(dtable[i-1][j+1]-dtable[i-1][j])/(dx[i+j]-dx[i+j-1]);
        }
    }
}
double Widget::newton(int x){
    if(x==num-1) return dtable[x][0];
    return dtable[x][0]+(tmpx-dx[x])*newton(x+1);
}

void Widget::on_PB_la_clicked()
{
    read();
    ui->LE_ans->setText(QString::number(lagrange()));
}

void Widget::on_PB_new_clicked()
{
    read();
    get_table();
    ui->LE_ans->setText(QString::number(newton(0)));
}
